package filters;

import java.io.File;
import java.util.Iterator;
import java.util.TreeSet;

public class FileWildCard extends AbstractWildCardFilter {
	
	protected FileWildCard() {
		_resultSet = new TreeSet<File>();
	}
	
	protected boolean validateParameter(String parameter) throws InvalidFilterParameterException{
		int wildcardOccureances=0;
		for(int i=0;i<parameter.length();i++) {
			if(parameter.charAt(i)=='*') {
				wildcardOccureances++;
			}
		}
		if(wildcardOccureances>2) {
			throw new InvalidFilterParameterException();
		}
		
		
		return true;
	}
	
	
	public TreeSet<File> filter(TreeSet<File> global,String parameter){
		for(Iterator<File> it1=global.iterator();it1.hasNext();) {
			File _tmpFile = it1.next();
			String[] fileNameSplitted = _tmpFile.getName().split("/");
			String fileName = fileNameSplitted[fileNameSplitted.length-1];
			if(parameter.startsWith("*") && parameter.endsWith("*")) {
				if(fileName.contains(parameter.subSequence(1, parameter.length()-1))) {
					_resultSet.add(_tmpFile);
				}
			}
			if(parameter.startsWith("*") && !parameter.endsWith("*")) {
				if(fileName.endsWith(parameter.subSequence(1, parameter.length()).toString())) {
					_resultSet.add(_tmpFile);
				}	
			}
			if(!parameter.startsWith("*") && parameter.endsWith("*")) {
				if(fileName.startsWith(parameter.subSequence(0, parameter.length()-1).toString())) {
					_resultSet.add(_tmpFile);
				}	
			}
			if(!parameter.startsWith("*") && !parameter.endsWith("*")) {
				if(fileName.compareTo(parameter)==0) {
					_resultSet.add(_tmpFile);
				}	
			}
		}
		return _resultSet;
	}
	
}
